<template>
    <rx-layout>
        <div slot="left" width="220" showButton="true">
            <rx-fit>
                <rx-category-treeeditor
                    cat-key="FORM"
                    :statisticConfig="statisticConfig"
                    :edit="true"
                    @handSelect="handSelect"
                    :async="true"
                    v-if="isShowManageTree"
                    :isAdmin="isManageToTree"
                    :checkToDel="true"
                ></rx-category-treeeditor>
            </rx-fit>
        </div>
        <div slot="center">
            <rx-fit :isheader="isheader">
                <div slot="toolheader" foldheader="true" foldbtn="false" border="false">
                    <div class="table-operator">
                        <a-button type="primary" icon="plus" v-if="findAuthRight('add')" @click="add">
                            {{ $ti18('rxList.newBtn', '新建') }}
                        </a-button>
                        <a-button type="primary" v-if="!isAppDevelop && selectedRowKeys.length > 0 " icon="redo"
                                  @click="checkBeforeBatchChangesApp('FORM',selectedRows,'pkId','name','appId','treeId',changeAppId)">
                            {{ boentI18n('list.ChangeApplication', '变更应用') }}
                        </a-button>
                        <a-button type="primary"
                                  v-if="selectedRowKeys.length > 0"
                                  icon="switcher" @click="changeExport(exportConf)">
                            {{ $ti18('rxList.changeExport', '切换导出') }}
                        </a-button>
                        <a-button v-if="selectedRowKeys.length > 0"
                                  type="primary"
                                  icon="switcher" @click="openCategoryDialog">
                            {{ $ti18('rxList.changeCategory', '切换分类') }}
                        </a-button>
                    </div>
                    <span class="search-btn-box" v-if="!isheader">
                        <span class="search-btn" @click.stop="searchshow"><i class="iconfont iconguolv"></i>
                            {{ $ti18('rxList.leachBtn', '过滤') }}
                        </span>
                    </span>
                </div>
                <div btnalign="right" slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel"
                     @close="closeSearchbar">
                    <a-form :layout="colLayout">
                        <a-row :gutter="24">
                            <a-col :span="colSpan">
                                <a-form-item :label="boentI18n('form.name','名称')">
                                    <a-input :placeholder="boentI18n('form.name','名称','input')"
                                             v-model="queryParam.Q_NAME__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="boentI18n('form.alias','别名')">
                                    <a-input :placeholder="boentI18n('form.alias','别名','input')"
                                             v-model="queryParam.Q_ALIAS__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan" v-if="!curApp.appId">
                                <a-form-item :label="$ti18('rxForm.appId', '应用')">
                                    <rx-search-app @change="appChange" v-model="searchApps">
                                    </rx-search-app>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan" v-if="isheader">
                      <span class="table-page-search-submitButtons">
                        <a-button type="primary" icon="search" @click="search">
                            {{ $ti18('rxList.searchBtn', '查询') }}
                        </a-button>
                        <a-button style="margin-left: 4px" @click="cancel">
                            {{ $ti18('rxList.resetBtn', '重置') }}
                        </a-button>
                        <a @click="toggleAdvanced" style="margin-left: 8px">
                          {{ advanced ? $ti18('rxList.putAwayBtn', '收起') : $ti18('rxList.openBtn', '展开') }}
                          <a-icon :type="advanced ? 'up' : 'down'"/>
                        </a>
                      </span>
                            </a-col>
                            <template v-if="advanced">
                                <a-col :span="colSpan">
                                    <a-form-item :label="boentI18n('form.gendb','生成库')">
                                        <a-select allowClear v-model="queryParam.Q_SUPPORT_DB__I_EQ">
                                            <a-select-option key="1">
                                                {{ boentI18n('list.yes', '是') }}
                                            </a-select-option>
                                            <a-select-option key="0">
                                                {{ boentI18n('list.no', '否') }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                            </template>
                        </a-row>
                    </a-form>
                </div>
                <rx-grid
                    ref="table"
                    :bordered="isBorder"
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :columns="columns"
                    :defaultPageSize="10"
                    url="/api-form/form/bo/formBoDef/query"
                    :queryParam="queryParam"
                    data-field="result.data"
                    :pageSizeOptions="['10', '30', '40']"
                    id-field="id"
                    :loadDataOnstart="true"
                    @selectChange="onSelectChange"
                >
                    <span slot="exportApp">
                         {{ exportI18n('export.isExport', '导出') }}
                        <export-app/>
                    </span>
                    <span slot="genType" slot-scope="{ text, record }">
                        <a-tag :color="genTypeMap[text].color">
                          <span>{{ genTypeMap[text].text }}</span>
                        </a-tag>
                    </span>
                    <span slot="supportDb" slot-scope="{ text, record }">
                        <a-tag :color="supportDbMap[text].color">
                          <span>{{ supportDbMap[text].text }}</span>
                        </a-tag>
                    </span>
                    <span slot="appId" slot-scope="{ text, record }">
                        {{ allApps[text] ? $i18(allApps[text].appName, '应用名称') : $ti18('rxList.noAppName', '无') }}
                    </span>
                    <span slot="isExport" slot-scope="{ text, record }">
                        <a-tag :color="text == 1 ? 'green' : 'red'">
                            <span>{{ text == 1 ? exportI18n('export.yes', '是') : exportI18n('export.no', '否') }}</span>
                        </a-tag>
                    </span>
                    <span slot="action" slot-scope="{ text, record }" class="actionIcons">
                        <span v-if="findAuthRight('edit')" @click.stop="boManage(record.id)">
                          {{ i18n('list.manage', '管理') }}
                        </span>
                        <span v-if="findAuthRight('edit') && editEnable" @click.stop="edit(record)">
                          {{ $ti18('rxList.editBtn', "编辑") }}
                        </span>
                        <span @click="templateSelect(record)" :title="i18n('list.templateEdit','模板编辑')">
                            {{i18n('list.templateEdit','模板编辑')}}
                        </span>
                        <span v-if="findAuthRight('delete') && removeEnable" @click.stop="delByIds([record.id])">
                            {{ $ti18('rxList.delBtn', '删除') }}
                        </span>
                        <span @click="setExport(record,exportConf)">{{ record.isExport == 1 ? exportI18n('export.noExport', '不导出') : exportI18n('export.exported', '导出') }}</span>
                    </span>
                </rx-grid>
                <a-modal
                    :title="$ti18('rxMsa.delInfo','您确定需要删除选中的记录吗?')"
                    style="top: 100px;"
                    :width="400"
                    v-model="visible"
                    :confirmLoading="confirmLoading"
                    @ok="handleOk"
                >
                    <a-checkbox v-model="delEntity">
                        {{ i18n('list.delEntity', '删除实体') }}
                    </a-checkbox>
                </a-modal>
                <a-modal v-model="changeAppVisible" :title="changeAppMessage" @ok="handleOkApp">
                    <div class="modal-erro">
                        <div class="modal-head">
                            <div class="modal-head-name">{{ comment }}</div>
                            <div class="modal-head-name">{{ boentI18n('list.comment', '业务实体') }}</div>
                        </div>
                        <div class="modal-common" v-for="item in changeAppMessages">
                            <div class="modal-head-name">{{ item.boDefName }}</div>
                            <div class="modal-head-name">{{ item.boEntNames }}</div>
                        </div>
                    </div>
                </a-modal>
            </rx-fit>
        </div>
    </rx-layout>
</template>

<script>
import FormBoDefApi from '@/api/form/bo/formBoDef'
import FormBoDefEdit from './FormBoDefEdit'
import {BaseList, Util} from "@lowcode/jpaas-common-lib"
import FormBoDefManager from './FormBoDefManager'
import FormBoDefJson from './FormBoDefJson'
import FormBoDefForm from './FormBoDefForm'
import RxCategoryTreeeditor from '@/components/redxun/rx-category-treeeditor'
import {mapMutations, mapState} from 'vuex'
import FormWordTemplateList from "@/views/modules/form/core/FormWordTemplateList";
import changeAppJs from "@/views/modules/share/changeApp";
import exportApp from "@/views/modules/share/exportApp";
import FormExcelTemplateList from "./FormExcelTemplateList.vue";
import AppSearch from "@/views/modules/share/AppSearch";
import RxSearchApp from "@/views/modules/share/rx-search-app";
import FormPdfTemplateList from "@/views/modules/form/core/FormPdfTemplateList";
import FormPrintLodopList from "@/views/modules/form/core/FormPrintLodopList.vue";
import switchExport from "@/utils/switchExport";
import ChangeCategory from "@/views/modules/share/ChangeCategory.js"
import OpenTemplate from "./OpenTemplate.vue";
export default {
    name: 'FormBoDefList',
    mixins: [BaseList, changeAppJs, AppSearch, switchExport, ChangeCategory],
    components: {
        FormBoDefEdit,
        RxCategoryTreeeditor,
        exportApp,
        RxSearchApp
    },
    filters: {},
    computed: {
        ...mapState({
            navigation: state => state.appSetting.navigation,
            activeKey: state => state.appSetting.activeKey,
            showType: (state) => state.appSetting.showType,
            allApps: state => state.appSetting ? state.appSetting.allApps : {}
        })
    },
    data() {
        return {
            changeAppVisible: false,
            changeAppMessage: this.i18n('msg.changeAppMessage', '当前业务模型对应实体所属应用不相同'),
            changeAppMessages: [],
            columns: [
                {
                    title: this.$ti18('rxList.index', '序号'),
                    type: 'indexColumn',
                    width: 60,
                    dataIndex: 'serial',
                    scopedSlots: {customRender: 'serial'},
                },
                {
                    title: this.boentI18n('form.name', '名称'),
                    dataIndex: 'name',
                    sorter: true,
                    sortField: 'NAME_',
                    width: '140%'
                },
                {
                    title: this.boentI18n('form.alias', '别名'),
                    dataIndex: 'alias',
                    sorter: true,
                    sortField: 'ALIAS_',
                    width: '120%'
                },
                {
                    title: this.boentI18n('form.genMode', '创建方式'),
                    dataIndex: 'genType',
                    sorter: true,
                    sortField: 'GEN_TYPE_',
                    width: '120%',
                    scopedSlots: {customRender: 'genType'}
                },
                {
                    title: this.boentI18n('form.gendb', '生成库'),
                    dataIndex: 'supportDb',
                    width: '110%',
                    scopedSlots: {customRender: 'supportDb'}
                },
                {
                    title: this.boentI18n('form.app', '所属应用'),
                    dataIndex: 'appId',
                    width: 100,
                    sortField: 'APP_ID_',
                    scopedSlots: {customRender: 'appId'}
                },
                {
                    // title: this.exportI18n('export.isExport','是否导出'),
                    dataIndex: 'isExport',
                    slots: {title: 'exportApp'},
                    width: 100,
                    scopedSlots: {customRender: 'isExport'}
                },
                {
                    title: this.$ti18('rxForm.createTime', '创建时间'),
                    dataIndex: 'createTime',
                    sorter: true,
                    sortField: 'CREATE_TIME_',
                    width: '140%'
                },
                {
                    title: this.$ti18('rxList.action', '操作'),
                    dataIndex: 'action',
                    fixed: 'right',
                    scopedSlots: {customRender: 'action'},
                    width: '120%'
                },
            ],
            component: FormBoDefEdit,
            comment: this.i18n('list.comment', '业务模型'),
            widthHeight: ['900px', '550px'],
            genTypeMap: {
                form: {color: 'green', text: this.boentI18n('genModeMap.form', '表单')},
                direct: {color: 'red', text: this.boentI18n('genModeMap.design', '设计')},
                easyform: {color: 'blue', text: this.boentI18n('genModeMap.easyForm', '拖动表单')},
                dragform: {color: 'blue', text: this.boentI18n('genModeMap.easyForm', '拖动表单')}
            },
            supportDbMap: {
                1: {color: 'green', text: this.boentI18n('list.yes', '是')},
                0: {color: 'red', text: this.boentI18n('list.no', '否')},
            },
            curTree: {},
            delEntity: false,
            visible: false,
            confirmLoading: false,
            statisticConfig: {
                type: "static_form",
                table: "FORM_BO_DEF t",
                field: "TREE_ID_",
                whereConf: []
            },
            /**
             * 导出配置
             */
            exportConf: {
                Api: FormBoDefApi,
                id: "id"
            },
            //变更分类配置
            categoryConfig: {
                Api: FormBoDefApi,
                catKey: "FORM",
                gridRef: "table"
            }
        }
    },
    created() {
        this.isUserManager(this.$route.query.appId);
        this.needFilterAppId("isAppMenu");
        this.columns = this.removeAppColumn(this.curApp.appId, this.columns)
    },
    methods: {
        ...mapMutations('appSetting', ['setActiveKey']),
        handleOkApp(e) {
            this.changeAppVisible = false;
            this.changeAppMessages = [];
        },
        checkBeforeBatchChangesApp(catKey, selectedRows, pkId, name, appId, categoryId, saveClick) {
            let boDefList = [];
            for (let i = 0; i < selectedRows.length; i++) {
                boDefList.push(selectedRows[i].pkId);
            }
            let self_ = this;
            FormBoDefApi.checkBeforeBatchChangesApp(boDefList).then(res => {
                if (!res.success) {
                    self_.changeAppVisible = true;
                    self_.changeAppMessages = res.data;
                    return;
                }
                self_.changeApp(catKey, selectedRows, pkId, name, appId, categoryId, saveClick);
            });
        },
        i18n(name, text, key) {
            return this.$ti18(name, text, "formBoDef", key);
        },
        boentI18n(name, text, key) {
            return this.$ti18(name, text, "formBoEntity", key);
        },
        exportI18n(name, text, key) {
            return this.$ti18(name, text, "appExport", key);
        },

        delByIds(ids) {
            this.selectedRowKeys = ids;
            this.visible = true;
            this.delEntity = false;
        },
        handleOk() {
            FormBoDefApi.del({ids: this.selectedRowKeys.join(','), delEntity: this.delEntity}).then(res => {
                if (res.success && res.code == 200) {
                    this.$refs.table.loadData();
                }
                this.selectedRowKeys = [];
                this.selectedRows = [];
                this.confirmLoading = false;
                this.visible = false;
            })
        },
        getListByParams(parameter) {
            return FormBoDefApi.query(parameter)
        },
        boManage(id) {
            var baseConf = {
                curVm: this,
                component: FormBoDefManager,
                title: this.i18n('list.MangBo', '管理BO'),
                widthHeight: ['1000px', '700px'],
                data: {
                    pkId: id,
                    callback: function (data) {
                        console.info(data)
                    },
                },
            }
            Util.open(baseConf, function (action) {
            })
        },
        viewJson(id) {
            var baseConf = {
                curVm: this,
                component: FormBoDefJson,
                title: this.i18n('list.jsonData', 'JSON数据'),
                widthHeight: ['800px', '600px'],
                data: {
                    pkId: id,
                    callback: function (data) {
                        console.info(data)
                    },
                },
            }
            Util.open(baseConf, function (action) {
            })
        },
        relationForm(id) {
            var baseConf = {
                curVm: this,
                component: FormBoDefForm,
                title: this.i18n('list.assForm', '关联表单'),
                widthHeight: ['800px', '700px'],
                data: {
                    pkId: id,
                    callback: function (data) {
                        console.info(data)
                    },
                },
            }
            Util.open(baseConf, function (action) {
            })
        },
        handSelect(curRow) {
            this.curTree = curRow;
            var treeId = curRow.treeId
            if (treeId != "0") {
                this.queryParam.Q_TREE_ID__S_EQ = treeId;
            } else {
                delete this.queryParam.Q_TREE_ID__S_EQ;
            }
            this.loadData(this.queryParam);
        },
        search() {
            this.$refs.table.loadData();
        },
        cancel() {
            this.resetSearch()
        },
        closeSearchbar() {
            //关闭过滤弹窗；（点击X触发）
            this.fitSearch = false;
        },
        templateSelect(record){
            let config = {
                curVm:this,
                component:OpenTemplate,
                max:true,
                data:{
                    config:record
                }
            }
            Util.open(config,()=>{})
        },

        changeAppId(selectedRows) {
            FormBoDefApi.batchChangesApp(selectedRows);
        }
    },
}
</script>
<style scoped>
.modal-erro {
    border: 1px solid #e8e8e8;
    border-radius: 5px;
    border-bottom: none;
    border-right: none;
}

.modal-head, .modal-common {
    display: flex;
    width: 100%;
}

.modal-head-name {
    flex: 1;
    border-bottom: 1px solid #e8e8e8;
    padding: 10px 20px;
    border-right: 1px solid #e8e8e8;
}
</style>

